import http from '@ohos.net.http';
import usb from '@ohos.usb';

function STR(str:string){

  //得到数据
  var l1=str.split("\"body\":\"")
  var ty=l1[1].split("\"")
 // console.info('headerB:'+ty[0] );

  var data_p=ty[0].split("255");

 // data_p.forEach(el =>console.info(el.length+"header0:"+el))
  var final_data=data_p[0].split("a");
  for (let i = 1; i < data_p.length; i++) {
    if(data_p[i].split("a").length>final_data.length){
      final_data=data_p[i].split("a")
    }
  }
  if(final_data.length>=75) {
    console.info('headerB:' + final_data.length + "#" + final_data);
    console.info('header心率:' + final_data.length + "#" + final_data[64]);
    console.info('header血氧:' + final_data.length + "#" + final_data[65]);
    console.info('header微循环:' + final_data.length + "#" + final_data[66]);
    console.info('header疲劳指数：:' + final_data.length + "#" + final_data[67]);
    console.info('header收缩压：:' + final_data.length + "#" + final_data[70]);
    console.info('header舒张压：:' + final_data.length + "#" + final_data[73]);
    console.info('header心输出：:' + final_data.length + "#" + final_data[74]);
    console.info('header外周阻力：:' + final_data.length + "#" + final_data[75]);
    console.info("--------------------------");
  }

}



export function requestUrl(url:string,callback:(result)=>void){

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.GET,
    header:{
      'Content-Type':'application/json',
      'X-Auth-Token':'MIIP2wYJKoZIhvcNAQcCoIIPzDCCD8gCAQExDTALBglghkgBZQMEAgEwgg3tBgkqhkiG9w0BBwGggg3eBIIN2nsidG9rZW4iOnsiZXhwaXJlc19hdCI6IjIwMjQtMDQtMTRUMDc6MDQ6NTUuMzg2MDAwWiIsIm1ldGhvZHMiOlsicGFzc3dvcmQiXSwiY2F0YWxvZyI6W10sInJvbGVzIjpbeyJuYW1lIjoidGVfYWRtaW4iLCJpZCI6IjAifSx7Im5hbWUiOiJ0ZV9hZ2VuY3kiLCJpZCI6IjAifSx7Im5hbWUiOiJvcF9nYXRlZF9jc2JzX3JlcF9hY2NlbGVyYXRpb24iLCJpZCI6IjAifSx7Im5hbWUiOiJvcF9nYXRlZF9lY3NfZGlza0FjYyIsIml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Q6NTUuMzg2MDAwWiIsInVzZXIiOnsiZG9tYWluIjp7Im5hbWUiOiJoaWRfcW9hMHhubHdxOW8wdThiIiwiaWQiOiIyNzYwMWFmZmU4ZTM0OWYxOWFiYTA4YmRjMTBmNGVjMCJ9LCJuYW1lIjoicHlzdXNlciIsInBhc3N3b3JkX2V4cGlyZXNfYXQiOiIiLCJpZCI6IjU1NTQ5M2QzMTkxMTRlOGJiYTFkNjNhNDk0MTFmNDQzIn19fTGCAcEwggG9AgEBMIGXMIGJMQswCQYDVQQGEwJDTjESMBAGA1UECAwJR3VhbmdEb25nMREwDwYDVQQHDAhTaGVuWmhlbjEuMCwGA1UECgwlSHVhd2VpIFNvZnR3YXJlIFRlY2hub2xvZ2llcyBDby4sIEx0ZDEOMAwGA1UECwwFQ2xvdWQxEzARBgNVBAMMCmNhLmlhbS5wa2kCCQDcsytdEGFqEDALBglghkgBZQMEAgEwDQYJKoZIhvcNAQEBBQAEggEAJ-Oo-Mg9eLIT9p5V8OO3ZFMEsTgdegpq+fa9QhoiTw0diTiEXqm7nFMtAKGKsqY8SrOiWxTiuF4W4rsOwCjLBEHbV7iDtpvBPrZsbfwmVrax8gVMHYvy1eVpIy0d4mtDK0xwsEtJKYVAlkt2mb26uDwl5V3cTXP6M9Ti6hEXojQ3IA1yxZov2MBoyV2wY0BV4ZOkJL6QumjdRtWc8vLNgos77jfycDQYR8uXirkUSLp+DAcw26P8-suKI6dpE9YkRuU8EwqpDY9mApiZLqF4hRY2cVW84VSOGZkPgjj8GSUxEHngsmjrsJxChSzvv6vn8PrLy3TH1UaOMF0ZOwFp6w=='
    },
    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    //console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{

    console.info('header:'+data.result.toString());//.substring(0,50)
    //STR(data.result.toString())


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}



//获得历史数据
export function requestUrlLSData(url:string,callback:(result)=>void){

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.GET,

    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    //console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{

    console.info('header:'+data.result.toString());//.substring(0,50)
    //STR(data.result.toString())


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}



//获得模型评估结果
export function requestUrlBody(url:string,callback:(result)=>void){

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.GET,

    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    //console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{

    console.info('header:'+data.result.toString());//.substring(0,50)
    //STR(data.result.toString())


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}


//获取token
export function requestToken(url:string,callback:(result)=>void){

  let json_data=JSON.stringify('{"auth": {"identity": { "methods": ["password"  ],  "password": { "user": {   "name": "pysuser",  "password": "huawei987654321",  "domain": {  "name": "hid_qoa0xnlwq9o0u8b"  }   }  }  }, "scope": { "project": {   "name": "cn-north-4"  }   } } }')
  let json2={
    auth: {
      identity: {
        methods: "password",
        password: {
          user: {
            name: "pysuser",
            password: "huawei987654321",
            domain: {
              name: "hid_qoa0xnlwq9o0u8b"
            }
          }
        }
      },
      scope: {
        project: {
          name: "cn-north-4"
        }
      }
    }
  }
  console.info('header_json:'+JSON.stringify(json2));

  let httpRequest = http.createHttp();
  let requestOptions = {
    method:http.RequestMethod.POST,
    header:{
      'Content-Type':'application/json;charset=UTF-8'
       },
     extraData:{
       'body':JSON.stringify(json2)
     },




    connectTimeout:30000,
    readTimeout:30000,
  }

  httpRequest.on('headersReceive',(header)=>{
    console.info('header:'+JSON.stringify(header));
  });

  let res =httpRequest.request(url,requestOptions)
  res.then((data)=>{
    console.info('header-1:'+data.result.toString());//.substring(0,50)
    console.info('header0:'+data.responseCode.toString());
    console.info('header1:'+data.header.toString());
    console.info('header2:'+JSON.stringify(data.header));



    let deviceList = usb.getDevices();
    let deviceName = deviceList[0].name;
    console.info('headerUSBList:'+deviceList);
    console.info('headerUSB:'+deviceName);

    // 申请操作指定的device的操作权限。
    usb.requestRight(deviceName).then(hasRight => {
      console.info("usb device request right result: " + hasRight);
    }).catch(error => {
      console.info("usb device request right failed : " + error);
    });

    // 打开设备，获取数据传输通道。
    let pipe = usb.connectDevice(deviceList[0]);
    let interface1 = deviceList[0].configs[0].interfaces[0];
    /*
     打开对应接口，在设备信息（deviceList）中选取对应的interface。
    interface1为设备配置中的一个接口。
    */
    usb.claimInterface(pipe , interface1, true);

    /*
 读取数据，在device信息中选取对应数据接收的endpoint来做数据传输
（endpoint.direction == 0x80）；dataUint8Array是要读取的数据，类型为Uint8Array。
*/
    let inEndpoint = interface1.endpoints[2];
    let outEndpoint = interface1.endpoints[1];
    outEndpoint.direction==0x8A
    let dataUint8Array = new Uint8Array(1024);
    usb.bulkTransfer(pipe, inEndpoint, dataUint8Array, 15000).then(dataLength => {
      if (dataLength >= 0) {
        console.info("usb readData result Length : " + dataLength);
        let resultStr = this.ab2str(dataUint8Array); // uint8数据转string。
        console.info("usb readData buffer : " + resultStr);
      } else {
        console.info("usb readData failed : " + dataLength);
      }
    }).catch(error => {
      console.info("usb readData error : " + JSON.stringify(error));
    });
    // 发送数据，在device信息中选取对应数据发送的endpoint来做数据传输。（endpoint.direction == 0）
    usb.bulkTransfer(pipe, outEndpoint, dataUint8Array, 15000).then(dataLength => {
      if (dataLength >= 0) {
        console.info("usb writeData result write length : " + dataLength);
      } else {
        console.info("writeData failed");
      }
    }).catch(error => {
      console.info("usb writeData error : " + JSON.stringify(error));
    });


    callback(data.result)
  }).catch((err)=>{
    console.info('header err:'+err);
    httpRequest.destroy();
  })


}